/**
 * 
 * @author  Stephan Marc Hansen
 */
package com.kea.firsthorse.server;

import com.kea.firsthorse.client.ConnectionService;
import com.kea.firsthorse.shared.FieldVerifier;
import com.kea.firsthorse.shared.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class ConnectionServiceImpl extends RemoteServiceServlet implements
		ConnectionService {

	@Override
	public User greetServer(String id, String pwhash)
			throws IllegalArgumentException {
		User result = null;
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(id)
				|| !FieldVerifier.isValidPWHash(pwhash)) {
			// If the input is not valid, throw an IllegalArgumentException back
			// to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		// Escape data from the client to avoid cross-site script
		// vulnerabilities.
		System.out.println("I="+id + ",H="+pwhash);
		id = escapeHtml(id);
		pwhash = escapeHtml(pwhash);
		
		DataController d = new DataController();
		System.out.println("I="+id + ",H="+pwhash);
		if (d.validate_user(Integer.parseInt(id), pwhash)){
			System.out.println("User Matched, retrieving user object");
			result = d.getUserData(Integer.parseInt(id));
		}
		return result;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
